import { Injectable } from "@angular/core";
import { SqliteService } from "./sqliteDB/sqlite.service";
import {SecureStorageService} from './secure-storage.services';
import { Platform } from 'ionic-angular';
import {Observable} from "../../../../node_modules/rxjs";
import { UtilsService } from "./utils.services";
import { EncryptService } from "./encrypt.service";


declare var window: {
  cordova,
  localStorage: {
    removeItem: any,
    setItem: any
  }
};

declare const ENV: {
  environment: any,
  baseUrl: any
};

declare let navigator: any;

@Injectable()
export class LogonService {


  constructor(private dbservice: SqliteService,
              private secureStorageService: SecureStorageService,
              private platform: Platform,
              private util: UtilsService,
              private encryptService: EncryptService) {
  }

  logout() {
    this.secureStorageService.clearToken();
    window.localStorage.removeItem('role');
    return Observable.create((obscriber) => {
      if (navigator.Login) {
        // navigator.Login.logout();
        navigator.Login.logoutAndroid( () => {
          obscriber.next();
          obscriber.complete();
          // this.util.hiddenLoading();
          // this._startApp(this.platform.is("ios") ? (this.appInfo.application.deeplinkScheme + "://") : this.appInfo.application.id, []);
        });
      } else {
        obscriber.next();
        obscriber.complete();
      }
    });

  }

  loginVPN() {
    if (!window.cordova || ENV.environment === "dev") {
      return this.encryptService.getPublic();
    }

    let ob: Observable<any>;

    // if (this.plt.is('android')) {
    return Observable.create((subcriber) => {
      navigator.Login.login(
        () => {
          ob = this.encryptService.getPublic();
          ob.subscribe(() => {
            subcriber.next();
            subcriber.complete();
          });
        },
        () => { subcriber.error(); this.util.tip("VPN 连接失败"); },
        "https://202.101.77.206:443",
        "szwd",
        "Gzdw1234");
    });
  }

  saveUserData(data) {
    // this.role = data['role'];
    this.secureStorageService.set("access_token", data['access_token']);
    this.secureStorageService.set('refresh_token', data['refresh_token']);
    this.secureStorageService.set('qixinAccount', data['qixinAccount']);
    this.secureStorageService.set('loginAccount', data['loginAccount']);
    this.secureStorageService.set('loginUserName', data['userName']);
    window.localStorage.setItem('role', data['role']);
  }




}
